package com.cib.yym.homepage.common.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;

import com.cib.yym.homepage.common.CacheManager;


public class GAECacheManager implements CacheManager{

	private static GAECacheManager instance = null;
	Cache cache = null;
	
	
	private GAECacheManager() {
		try {
			cache = net.sf.jsr107cache.CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e) {			
			e.printStackTrace();
		}
	}

	public static synchronized GAECacheManager getInstance() {
		if (instance == null) {
			instance = new GAECacheManager();
		}
		return instance;
	}
	
	public void clearCache(String mapName) {
		cache.put(mapName, null);	
	}

	public Map<String, Object> getCacheMap(String mapName) {
		if(cache.get(mapName) == null)
		{
			cache.put(mapName, new HashMap<String,Object>());
		}
		return (Map<String, Object>) cache.get(mapName);
	}

	public Object getCachedData(String mapKey, String key) {
		Map tmp = (Map) cache.get(mapKey);		
		return tmp.get(key);
	}
	
	public void updateCache(String mapName, String key, Object value) {
		try {
			Map tmp = (Map) cache.get(mapName);
			if(tmp == null)
			{
				tmp = new HashMap<String,Object>();
			}
			tmp.put(key, value);
			cache.put(mapName, tmp);
		} catch (Exception e) {
			e.printStackTrace();		
		}
	}

}
